package com.tools;

public class CRC {
	
	private static int[]  crc_tabkermit = new int[256];
	private static boolean crc_tabkermit_init = false;
	
	public static byte[] calculate_crc_kermit(byte[] bytes){
		
		int value = 0;
		byte[] result = new byte[2];
		
		for(int i = 0; i < bytes.length; i++){

			value = CRC.update_crc_kermit(value, bytes[i]);
		}
		
		result[0] = (byte) (value & 0x00ff);
		result[1] = (byte) ((value & 0xff00) >> 8);
		
		return result;
	}
	
	private static int update_crc_kermit( int crc, byte c ) {

	    int tmp, int_c;

	    int_c = (int) (0x00ff & (int) c);
	    
	    if ( ! crc_tabkermit_init ) init_crckermit_tab();

	    tmp =  (int) (crc ^ int_c);
	    crc = (int) ((crc >> 8) ^ crc_tabkermit[ tmp & 0xff ]);

	    return crc;

	}  
	
	private static void init_crckermit_tab(  ) {

	    int i, j;
	    int crc;
	    int c;

	    for (i=0; i<256; i++) {

	        crc = 0;
	        c   = ( int) i;

	        for (j=0; j<8; j++) {

	            if ( ((crc ^ c) & 0x0001) == 1) crc = (int) (( crc >> 1 ) ^ 0x8408);
	            else                      crc =   (int) (crc >> 1);

	            c = (int) (c >> 1);
	        }

	        crc_tabkermit[i] = crc;
	    }

	    crc_tabkermit_init = true;
	}  /* init_crckermit_tab */
}
